#pragma once
#include <sys/epoll.h>
#include "Common.hpp"
#include "Log.hpp"

static const int gsize = 128;
class Multiplex
{
public:
    Multiplex() {}
    // EPOLL_CTL_ADD / EPOLL_CTL_DEL / EPOLL_CTL_MOD
    virtual bool AddEvent(int fd, uint32_t event) = 0;
    virtual bool ModEvent(int fd, uint32_t event) = 0;
    virtual bool DelEvent(int fd) = 0;
    virtual int Wait(struct epoll_event events[], int num, int timeout) = 0;
};

class Epoller : public Multiplex
{
private:
    bool ModEventHelper(int fd, uint32_t event, int oper)
    {
        // 创建红黑树节点
        struct epoll_event ev;
        ev.data.fd = fd;
        ev.events = event;
        int n = epoll_ctl(_epfd, oper /*ADD、MOD、DEL*/, fd, &ev);
        if (n < 0)
        {
            LOG(ERROR, "epoll_ctl %d events is %s failed\n", fd, EventToString(event).c_str());
            return false;
        }
        return true;
    }

public:
    Epoller()
    {
        _epfd = epoll_create(gsize);
        if (_epfd < 0)
        {
            LOG(FATAL, "epoll_create error!\n");
            // 创建失败服务器直接崩溃
            exit(EPOLL_CREATE_ERROR);
        }
        LOG(INFO, "epoll_create success, epfd: %d\n", _epfd);
    }
    std::string EventToString(uint32_t event)
    {
        std::string eventstring;
        if (event & EPOLLIN)
            eventstring += "EPOLLIN";
        else if (event & EPOLLOUT)
            eventstring += "|EPOLLOUT";
        else if (event & EPOLLET)
            eventstring += "|EPOLLET";
        return eventstring;
    }
    bool AddEvent(int fd, uint32_t event) override
    {
        return ModEventHelper(fd, event, EPOLL_CTL_ADD);
    }
    bool ModEvent(int fd, uint32_t event)
    {
        return ModEventHelper(fd, event, EPOLL_CTL_MOD);
    }
    bool DelEvent(int fd)
    {
        return epoll_ctl(_epfd, EPOLL_CTL_DEL, fd, nullptr);
    }
    int Wait(struct epoll_event revs[], int num, int timeout)
    {
        return epoll_wait(_epfd, revs, num, timeout);
    }

private:
    int _epfd;
};